<template>
    <view class="container">

        <!-- logo区域 -->
        <view class="logo-wrap" @click="goto('/pages/index/index')">
            <image class="logo" src="@/static/images/logo.png"/>
            <view class='txt'>自由交流，管他性谁</view>
        </view>

		<view class="content-wrap">
			<view class="title-wrap">
				<text @click="forgotType = 1" :class="{active: forgotType == 1}">手机找回</text>
				<text @click="forgotType = 2" :class="{active: forgotType == 2}">邮箱找回</text>
			</view>

			<!-- 手机找回 -->
			<view class="form-wrap" :class="{active: forgotType == 1}">
				<!-- 基础表单校验 -->
				<uni-forms
					ref="mobileFormRef"
					:rules="mobileRules"
					:modelValue="mobileFormData"
				>
					<!-- 用户名 -->
					<uni-forms-item name="mobile">
						<uni-easyinput
							type="number"
							prefixIcon="phone"
							:placeholderStyle="placeholderStyle"
							v-model="mobileFormData.mobile"
							:maxlength="11"
							placeholder="请输入手机号"
							:primaryColor="global.THEME_COLOR"
						/>
					</uni-forms-item>
					
					<!-- 验证码 -->
					<uni-forms-item name="code">
						<view class="code-box">
							<uni-easyinput
								type="number"
								prefixIcon="locked" 
								:placeholderStyle="placeholderStyle" 
								v-model="mobileFormData.code" 
								:maxlength="6" 
								placeholder="请输入验证码"
								:primaryColor="global.THEME_COLOR"
							/>
							
							
							<button class="code-btn" :class="{active: rightMobile}" :disabled="!rightMobile" type="default" @click="sendCode">{{time ? '剩余' + time + 's' : '获取验证码'}}</button>    
						</view>
					</uni-forms-item>
				</uni-forms>
				<button class="login-btn" @click="showSetPasswordPopup">下一步</button>
				
				<!-- 底部 -->
				<view class="footer-wapper">
					<view @click="goto('/pages/password_login/index')">密码登录</view>
					<view @click="goto('/pages/register/index')" style="font-size: 36rpx;color: #E83915;">还没有账户</view>
					<view @click="goto('/pages/message_login/index')">短信登录</view>
				</view>
			</view>


			<!-- 邮箱找回 -->
			<view class="form-wrap" :class="{active: forgotType == 2}">
				<!-- 基础表单校验 -->
				<uni-forms ref="emailFormRef" :rules="emailRules" :modelValue="emailFormData">
					<!-- 用户名 -->
					<uni-forms-item name="email">
						<uni-easyinput
							prefixIcon="email"
							:placeholderStyle="placeholderStyle"
							v-model="emailFormData.email"
							:maxlength="30"
							placeholder="请输入邮箱"
							:primaryColor="global.THEME_COLOR"
						/>
					</uni-forms-item>
					
					<!-- 验证码 -->
					<uni-forms-item name="code">
						<view class="code-box">
							<uni-easyinput
								type="number"
								prefixIcon="locked" 
								:placeholderStyle="placeholderStyle" 
								v-model="emailFormData.code" 
								:maxlength="6" 
								placeholder="请输入验证码"
								:primaryColor="global.THEME_COLOR"
							/>
							
							<button class="code-btn" :class="{active: rightEmail}" :disabled="!rightEmail" @click="sendEmailCode">{{exprieTime ? '剩余' + exprieTime + 's' : '获取验证码'}}</button> 
						</view>
					</uni-forms-item>
				</uni-forms>
				<button class="login-btn" @click="showEmailSetPasswordPopup">下一步</button>
				
				<!-- 底部 -->
				<view class="footer-wapper">
					<view @click="goto('/pages/password_login/index')">密码登录</view>
					<view @click="goto('/pages/register/index')" style="font-size: 36rpx;color: #E83915;">还没有账户</view>
					<view @click="goto('/pages/message_login/index')">短信登录</view>
				</view>
			</view>
		</view>
    </view>

	<!-- 弹层 -->
	<uni-popup
      ref="popup"
      type="bottom"
      background-color="#fff"
      :mask-click="false"
  	>
		<view class="pwd-panel">
			<view class="title-wrap">
				<!-- 标题 -->
				<view class="title">设置新密码</view>
				<!-- 关闭按钮 -->
				<text class="close iconfont icon-guanbi" @click="closePopup"></text>
			</view>

			<uni-forms ref="formRef" :rules="rules" :modelValue="formData">
				<!-- 新密码 -->
				<uni-forms-item name="new_password">
				<uni-easyinput
					type="password"
					prefixIcon="locked-filled" 
					v-model="formData.new_password"
					:placeholderStyle="placeholderStyle"
					placeholder="请输入新密码"
					:maxlength="16"
					:primaryColor="global.THEME_COLOR"
				/>
				</uni-forms-item>
				
				<!-- 确认密码 -->
				<uni-forms-item name="repassword">
				<uni-easyinput
					type="password"
					prefixIcon="locked" 
					v-model="formData.repassword"
					:placeholderStyle="placeholderStyle"
					placeholder="请输入确认密码"
					:maxlength="16"
					:primaryColor="global.THEME_COLOR"
				/>
				</uni-forms-item>
			</uni-forms>
			<button class="save-btn" @click="handleSave">保&nbsp;&nbsp;存</button>
		</view>
  	</uni-popup>
</template>


<script setup lang="ts">
import { reqEmailForgotPasswordAPI, reqEmailForgotSendCodeAPI, reqMobileForgotPasswordAPI, reqMobileForgotSendCodeAPI } from '@/apis/user'
import { reactive, ref, computed, inject } from 'vue'
import { goto } from '@/utils/tools'


// 提示样式
const placeholderStyle = ref('font-size:14px')

// 全局属性
const global: any = inject('global')

// --------------------- 手机找回功能开始 ---------------------
const mobileFormData = reactive({
	mobile: '',
	code: ''
})

const mobileFormRef = ref()

// 找回方式
const forgotType = ref(1) 

// 验证规则
const mobileRules = {
	mobile: {
		rules: [
			{
				required: true,
				errorMessage: '手机号不能为空'
			},
			{
				validateFunction: function(rule:any, value:any, data:any, callback:any) {
					let reg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/
					if (!reg.test(value)) {
						callback('请输入正确格式的手机号!')
					}
					return true
				}
			}
		]
	},
	code: {
		rules: [{
			required: true,
			errorMessage: '验证码不能为空'
		}]
	}
}
// --------------------- 手机找回功能结束 ---------------------



// --------------------- 邮箱找回功能开始 ---------------------
const emailFormData = reactive({
	email: '',
	code: ''
})

const emailFormRef = ref()


// 验证规则
const emailRules = {
	email: {
		rules: [
			{
				required: true,
				errorMessage: '邮箱不能为空!'
			},
			{
				validateFunction: function(rule:any, value:any, data:any, callback:any) {
					let reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
					if (!reg.test(value)) {
						callback('请输入正确格式的邮箱!')
					}
					return true
				}
			}
		]
	},
	code: {
		rules: [{
			required: true,
			errorMessage: '验证码不能为空'
		}]
	}
}
// --------------------- 邮箱找回功能结束 ---------------------



// ---------------------- 发送验证码功能开始 ----------------------
const rightMobile = computed(() => {
	// 手机正则
	const pattern = /^1[3|5|7|8|9]\d{9}$/
	return pattern.test(mobileFormData.mobile)
})

// 过期时间
const time = ref(0)

// 发送手机验证码
const sendCode = async () => {
	if(time.value == 0) {
		// 请求验证码接口
		await reqMobileForgotSendCodeAPI(mobileFormData.mobile)
		
		uni.showToast({
			title: '发送验证码成功',
			duration: 1000
		})
		
		time.value = 60
		const intervalId = setInterval(() => {
			time.value--
			if(time.value == 0) {
				clearInterval(intervalId)
			}
		}, 1000)
	}
}



const rightEmail = computed(() => {
	// 邮箱正则
	const pattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
	return pattern.test(emailFormData.email)
})

// 过期时间
const exprieTime = ref(0)

// 发送邮箱验证码
const sendEmailCode = async () => {
	if(exprieTime.value == 0) {
		// 请求验证码接口
		await reqEmailForgotSendCodeAPI(emailFormData.email)
		
		uni.showToast({
			title: '发送验证码成功',
			duration: 1000
		})
		
		exprieTime.value = 60
		const intervalId = setInterval(() => {
			exprieTime.value--
			if(exprieTime.value == 0) {
				clearInterval(intervalId)
			}
		}, 1000)
	}
}
// ---------------------- 发送验证码功能结束 ----------------------



// ---------------------- 点击下一步功能开始 ----------------------
const popup = ref()
const formRef = ref()
const formData = reactive({
	new_password: '',
	repassword: '',
})

// 验证规则
const rules = {
	new_password: {
		rules: [
			{
				required: true,
				errorMessage: '新密码不能为空!'
			}
		]
	},
	repassword: {
		rules: [
			{
				required: true,
				errorMessage: '确认密码不能为空!'
			},
			{
				validateFunction: function(rule:any, value:any, data:any, callback:any) {
					if (value != formData.new_password) {
						callback('两次输入密码不一致!')
					}
					return true
				}
			}
		]
	}
}

// 打开手机设置新密码弹层
const showSetPasswordPopup = () => {
	formData.new_password = ''
	formData.repassword = ''
	mobileFormRef.value.validate().then((res:any) => {
    	popup.value.open('top')
	}).catch((err:any) => {
		console.log('err =', err);
	})
}

// 打开邮箱设置新密码弹层
const showEmailSetPasswordPopup = () => {
	formData.new_password = ''
	formData.repassword = ''
	emailFormRef.value.validate().then((res:any) => {
    	popup.value.open('top')
	}).catch((err:any) => {
		console.log('err =', err);
	})
}

// 关闭弹层
const closePopup = () => {
	popup.value.close()
}
// ---------------------- 点击下一步功能结束 ----------------------



// ---------------------- 保存新密码功能开始 ----------------------
const handleSave = () => {
  formRef.value.validate().then(async (res:any) => {
    
    // 手机找回
    if (forgotType.value == 1) {
      await reqMobileForgotPasswordAPI({
        mobile: mobileFormData.mobile,
        new_password: formData.new_password,
        repassword: formData.repassword,
        code: mobileFormData.code
      })
    } else { // 邮箱找回
      await reqEmailForgotPasswordAPI({
        email: emailFormData.email,
        new_password: formData.new_password,
        repassword: formData.repassword,
        code: emailFormData.code
      })
    }

    uni.showToast({
			title: '找回密码成功',
			duration: 1000
		})

    popup.value.close()

    setTimeout(() => {
      uni.navigateTo({ url: '/pages/password_login/index' })
    },1000)
    
	}).catch((err:any) => {
	})
}
// ---------------------- 保存新密码功能结束 ------------------
</script>


<style scoped lang="scss">
.container {

    // logo区域
    .logo-wrap {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        height: 400rpx;
        text-align: center;
        background-color: #fff;
        .logo {
            width: 400rpx;
		    height: 150rpx;
        }
        .txt {
            margin-top: 20rpx;
            color: #c9cccb;
			font-size: 24rpx;
        }
    }

	.content-wrap {
		background-color: #fff;
		.title-wrap {
			display: flex;
			justify-content: space-evenly;
			padding: 40rpx 0;
			font-size: 38rpx;
			font-weight: bold;
			.active {
				color: $uni-color-primary;
				border-bottom: 4rpx solid $uni-color-primary;
			}
		}
		// 表单区域
		.form-wrap {
			display: none;
			&.active {
				display: block;
			}
			padding: 30rpx;
			.code-box {
				display: flex;
				.code-btn {
					background-color: darkgray;
					width: 180rpx;
					height: 70rpx;
					line-height: 70rpx;
					color: #fff; 
					font-size: 24rpx;
					margin-left: 160rpx;
					&.active {
						background-color: $uni-color-primary;
					}
				}
			}
			.login-btn {
				background-color: #fff;
				color: $uni-color-primary;
				border-radius: 46rpx;
				border: 2rpx solid $uni-color-primary;
			}

			.footer-wapper {
				display: flex;
				justify-content: space-between;
				margin: 20rpx 0;
			}
		}
	}
}

// 弹层区域
.pwd-panel {
	padding: 0 10rpx 30rpx 10rpx;
	.title-wrap {
		display: flex;
		justify-content: space-between;
		padding: 24rpx 0;
		border-bottom: 2rpx solid #ccc;
		margin-bottom: 20rpx;
		.title {
			font-size: 32rpx;
			flex: 1;
			text-align: center;
			color: $uni-color-primary;
		}
		.close {
			color: #ccc;
			font-size: 40rpx;
		}
	}

	.save-btn {
		color: #fff;
		background-color: $uni-color-primary;
		width: 80%;
	}
}
</style>